package org.jaaksi.customviewdemo.util

import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import kotlin.experimental.inv


// 默认密钥是Period
fun encode(data: String, keys: CharArray = "Period".toCharArray()): String {
    val src = data.toCharArray()
    val length = src.size / 2
    for (i in 0 until length) {
        src[i * 2] = (src[i * 2].toInt() xor keys[i % 6].toInt()).toChar()
        if (src[i * 2].toInt() == 0) {
            src[i * 2] = keys[i % 6]
        }
    }
    return String(src)
}

fun decode(data: String, keys: CharArray = "Period".toCharArray()): String {
    val src = data.toCharArray()
    val length = src.size / 2
    for (i in 0 until length) {
        src[i * 2] = (src[i * 2].toInt() xor keys[i % 6].toInt()).toChar()
        if (src[i * 2].toInt() == 0) {
            src[i * 2] = keys[i % 6]
        }
    }
    return String(src)
}

fun decodeFile(file: File) {
    val json = file.readText()
    val originalJson = decode(json, "Period".toCharArray())
    val originalFile = File("${file.parentFile.absolutePath}/${file.name}.json")
    originalFile.writeText(originalJson)
}

fun decodeFile(file: File, keys: CharArray = "Period".toCharArray(), fileName: String = "${file.name}.json") {
    val json = file.readText()

    val originalJson = decode(json, keys)

    val originalFile = File("${file.parentFile.absolutePath}/$fileName")
    originalFile.writeText(originalJson)
}


fun encodeFile(
    file: File,
    keys: CharArray = "Period".toCharArray(),
    fileName: String = file.name.removeSuffix(".json")
) {
    val json = file.readText()

    val encodedData = encode(json, keys)

    val encodedFile = File("${file.parentFile.absolutePath}/$fileName")
    encodedFile.writeText(encodedData)
}

fun encodeFiles(dir: String) {
    File(dir).listFiles().forEach { file ->
        val json = file.readText()

        val encodedData = encode(json, "Period".toCharArray())
        val fileName = if (file.name.endsWith("pt_br_strings.xml")) "pt" else file.name.removeSuffix("_strings.xml")
        val encodedFile =
            File("${file.parentFile.absolutePath}/$fileName")
        encodedFile.writeText(encodedData)
        file.delete()

    }
}

fun enDecodeVideoOrImage(src: String, des: String) {
    val src_file = File(src)
    val des_file = File(des)
    try {
        val fis = FileInputStream(src_file)
        val fos = FileOutputStream(des_file)
        val buffer = ByteArray(1024)
        var count: Int
        var hasSet = false
        count = fis.read(buffer)
        while (count != -1) {

            if (!hasSet) {
                hasSet = true
                for (i in 0..63) {
                    buffer[i] = buffer[i].inv()
                }
            }
            fos.write(buffer, 0, count)
            count = fis.read(buffer)
        }
        fos.flush()
        fos.close()
        fis.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }




}